package be.vanderveer.services.webthumb;

import java.io.StringReader;
import java.net.URI;
import org.apache.commons.lang.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

/**
 * The response recieved from the webthumb API after a request for a status.
 * 
 * @author Roderik van der Veer
 */
public class WebThumbStatusResponse {

	private String webthumbid;
	private int width;
	private int height;
	private URI imagezip;
	private Status status;

	public static enum Status {
		COMPLETE, PROGRESS
	}

	public WebThumbStatusResponse(final String xml) {
		super();
		parseResponse(xml);
	}

	private void parseResponse(final String xml) {
		try {
			final SAXBuilder builder = new SAXBuilder();
			final Document doc = builder.build(new StringReader(xml));
			final Element el = doc.getRootElement().getChild("jobStatus").getChild("status");
			setWebThumbId(el.getAttributeValue("id"));
			setHeight(Integer.valueOf(el.getAttributeValue("browserHeight")));
			setWidth(Integer.valueOf(el.getAttributeValue("browserWidth")));
			if (!StringUtils.isBlank(el.getAttributeValue("pickup"))) {
				setImagezip(new URI(el.getAttributeValue("pickup")));
				setStatus(Status.COMPLETE);
			} else {
				setStatus(Status.PROGRESS);
			}
		} catch (final Exception e) {
			throw new RuntimeException("Something went wrong, check the stacktrace", e);
		}
	}

	/**
	 * Return the unique identifier for this specific thumbnail.
	 * 
	 * @return the unique identifier for this specific thumbnail
	 */
	public String getWebThumbId() {
		return webthumbid;
	}

	private void setWebThumbId(final String webthumbid) {
		this.webthumbid = webthumbid;
	}

	public int getHeight() {
		return height;
	}

	private void setHeight(final int height) {
		this.height = height;
	}

	public URI getImagezip() {
		return imagezip;
	}

	private void setImagezip(final URI imagezip) {
		this.imagezip = imagezip;
	}

	public int getWidth() {
		return width;
	}

	public Status getStatus() {
		return status;
	}

	private void setStatus(final Status status) {
		this.status = status;
	}

	private void setWidth(final int width) {
		this.width = width;
	}

	@Override
	public String toString() {
		return "WebThumbJobResponse: id=" + getWebThumbId() + " - status=" + getStatus() + " - height=" + getHeight() + " - width=" + getWidth() + " - imagezip=" + getImagezip();
	}
}
